const {getAskList, createAsk, updateAsk, delAsk, getAskOne} = require('../service/ask')
const {createLease} = require('../service/lease')
const {SuccessModel, ErrorModel} = require('../model/ResModel')
const {addRoleFailInfo} = require('../model/ErrorInfo')
const {flatData} = require('../utils/flatData')

const getAsk = async ({status, createTime = [], pageIndex = 0, pageSize = 10}) => {
  const result = await getAskList({status, createTime, pageIndex, pageSize})
  result.data = flatData(result.data)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const getAskMy = async (ctx, {status, createTime = [], pageIndex = 0, pageSize = 10}) => {
  const result = await getAskList({askId: ctx.session.user.user.id, status, createTime, pageIndex, pageSize})
  result.data = flatData(result.data)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const getAskYours = async (ctx, {status, createTime = [], pageIndex = 0, pageSize = 10}) => {
  const result = await getAskList({ownerId: ctx.session.user.user.id, status, createTime, pageIndex, pageSize})
  result.data = flatData(result.data)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const postAsk = async (ctx, {content, rent, startTime, endTime, houseId, status = 1}) => {
  const result = await createAsk({
    content,
    rent,
    startTime,
    endTime,
    houseId,
    status,
    askId: ctx.session.user.user.id
  })
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const patchAsk = async ({content, rent, startTime, endTime, reason, status, id}) => {
  const result = await updateAsk({content, rent, startTime, endTime, reason, status, id})
  if (result && status === 5) {
    const result = await createLease({content: '租房条例', askId: id, status: 1})
    return result ? new SuccessModel() : new ErrorModel(addRoleFailInfo)
  }
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const deleteAsk = async (id) => {
  const result = await delAsk(id)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

const getAskById = async (id) => {
  let result = await getAskOne(+id)
  return result ? new SuccessModel(result) : new ErrorModel(addRoleFailInfo)
}

module.exports = {
  getAsk,
  getAskMy,
  postAsk,
  patchAsk,
  deleteAsk,
  getAskById,
  getAskYours
}
